﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;
using Util.Extension;
using AntUnion.FrameWork.Util;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CodetypesController : BaseController
    {
        private readonly mtContext _context;

        public CodetypesController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
        }

        #region 类别列表
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取类别列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.TbCodetypes
                           select new
                           {
                               id = y.CtId,
                               codeType = y.CtName,
                               typeCode = y.CtCode,
                               remark = y.CtRemark,
                               creator = y.CtCreate,
                               createDate = y.CtCreateTime
                           };

                res.Data = await data.OrderBy(k => k.id).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                res.Count = data.Count();                
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加类别
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 添加类别
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(TbCodetype model)
        {
            Result res = new Result();
            try
            {
                if (!TbCodetypeExists(model.CtName))
                {
                    model.CtCreate = User.LoginName;
                    model.CtCreateTime = DateTimeUtil.Now;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "类别名称已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑类别信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            TbCodetype TbCodetype = await _context.TbCodetypes.FindAsync(id);
            if (TbCodetype == null)
            {
                return NotFound();
            }
            return View(TbCodetype);
        }
        /// <summary>
        /// 编辑类别信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(TbCodetype item)
        {
            Result res = new Result();
            try
            {
                if (!TbCodetypeExists(item.CtName, item.CtId))
                {
                    TbCodetype model = await _context.TbCodetypes.FindAsync(item.CtId);
                    if (model != null)
                    {
                        model.CtName = item.CtName;
                        //model.CtCode = item.CtCode;
                        model.CtUpdate = User.LoginName;
                        model.CtUpdateTime = DateTimeUtil.Now;
                        model.CtRemark = item.CtRemark;
                        model.CtNameEn = item.CtNameEn;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "类别不存在";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "类别名称已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除类别
        /// <summary>
        /// 删除单个类别
        /// </summary>
        /// <param name="id">类别ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                TbCodetype TbCodetype = await _context.TbCodetypes.FindAsync(id);
                List<TbCode> codes = await _context.TbCodes.Where(k => k.CoType.Contains(TbCodetype.CtCode)).ToListAsync();
                foreach (TbCode model in codes)
                {
                    _context.TbCodes.Remove(model);
                }
                _context.TbCodetypes.Remove(TbCodetype);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的类别ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbCodetype> userList = await _context.TbCodetypes.Where(k => list.Contains(k.CtId)).ToListAsync();
                foreach (TbCodetype model in userList)
                {
                    List<TbCode> codes = await _context.TbCodes.Where(k => k.CoType.Contains(model.CtCode)).ToListAsync();
                    foreach (TbCode code in codes)
                    {
                        _context.TbCodes.Remove(code);
                    }
                    _context.TbCodetypes.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">类别名称称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbCodetypeExists(string Name, int id = 0)
        {
            if (id == 0)
                return _context.TbCodetypes.Any(e => e.CtName == Name);
            else
                return _context.TbCodetypes.Any(e => e.CtId != id && e.CtName == Name);
        }
        #endregion
    }
}
